/*2S7LXljdWdGhrCxZ1MFl4i0/jcYg0CI/M/l35xRmsHHDM270ypZGxQFjXbKKRAXA*/
//主子表卡片
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createPage, ajax, base, toast, cardCache, getMultiLang, getBusinessInfo, createPageIcon } from 'nc-lightapp-front';
import { buttonClick, initTemplate, afterEvent, beforeEvent, pageInfoClick, afterEventForm } from './events';
import { APPCODE, PAGE_CODE, CARD_IDS, DATA_SOURCE, PKNAME, PATH } from '../consts';
import { cp2othersFun, mv2sortFun, checkMultiCode, linkToList } from '../utils';
import {dealSystemChange} from './utils/index'
import FormulaModal from '../../../public/components/FormulaModal';
import TransdefCacheUtil from '../utils/TransdefCacheUtil';
import AssidModal from '../../../public/components/assidModal';
import CopyCheckModal from '../../../public/components/CopyCheckModal';
import TransSortModal from '../containers/TransSortModal';
import AccountingBookModal from '../containers/AccountingBookModal';
import HeaderArea from '../../../public/components/HeaderArea';
import './index.less';
let { NCBackBtn } = base;
let { addCache, updateCache, getCacheById, getNextId, deleteCacheById } = cardCache;
import {onBatchChange} from './utils/onBatchChange.js';
class Card extends Component {
	constructor(props) {
		super(props);
		this.cacheUtil = new TransdefCacheUtil(this.props.ViewModel);
		let context = this.cacheUtil.getContext();
		let state = this.cacheUtil.getListState();
		if (state) {
			this.orgState = state;
		}
		if (context) {
			this.alldata = context;
		}
		this.formId = CARD_IDS.FORM_ID;
		this.tableId = CARD_IDS.TABLE_ID;
		this.pageId = PAGE_CODE.CARD;
		this.state = {
			assistModalShow: false,
			showCopyCheckModal: false,
			repeatData: null,
			noRepeatArr: [],
			formulaModalState: { show: false, callback: null, defaultValue: '' },
			assidModalState: { show: false, callback: null, defaultValue: [],isModalClose:false },
			transsortModalShow: false,
			accbookModalShow: false,
			showCheck:false,
			showBackBtn: false,
			isCopying: false, //是否处于复制中
			json:{},
			listItem:{}
		};
		this.keyAssItems = 'assItems';
		this.keyAssValues = 'assValues';
		this.keyAss = 'ass';
		this.pk_accountingbook = this.props.getUrlParam('pk_accountingbook');
		this.pk_transsort = this.props.getUrlParam('pk_transsort');
		this.pk_transfer = this.props.getUrlParam('id');
		props.use.form(this.formId);
		props.use.cardTable(this.tableId);
	}
	componentWillMount() {
		let callback = (json, status, inlt) => {
			if(status){
				this.setState({json, inlt}, () => {
					initTemplate.call(this, this.props);
				})
			}else{
			}
		}

		getMultiLang({moduleId:'20020SDTRD', domainName:'gl', callback});
	}
	componentDidMount() {
		//关闭浏览器
        window.onbeforeunload = () => {
            let status=this.props.form.getFormStatus(this.formId);
            if (status == 'edit' || status == 'add') {
                return ''
            }
		}
		this.toggleShow();
		this.props.button.setButtonVisible(['paste2endline', 'cancel_copy'], false);
		let pk_transfer = this.props.getUrlParam('id');
		if (pk_transfer) this.getData(pk_transfer);
	}

	initAddPage = () =>{
		let page = this;
		let buziInfo = getBusinessInfo();
		let itemsValue = {
			pk_operator:{value:buziInfo.userId, display:buziInfo.userName}
		}
		page.clearPageData();
		page.props.form.setFormItemsValue(page.formId, itemsValue);
        page.props.cardTable.addRow(CARD_IDS.TABLE_ID, 0, {}, false);
        page.props.form.setFormItemsDisabled(CARD_IDS.FORM_ID, {
            [CARD_IDS.FORM_TRANSITMELIMIT]:false,
            [CARD_IDS.FORM_FREQUENCY]:false
        });
	}

	//查询单据详情
	getData = (pk_transfer) => {
		if (!pk_transfer) {
			this.clearPageData();
			return;
		}
		let cardData = getCacheById(pk_transfer, DATA_SOURCE);
		if (cardData) {
			this.loadData(cardData);
			return;
		}
		this.refresh(pk_transfer);
	};

	refresh = (pk_transfer, callback) => {
		if(!pk_transfer) return;
		let page = this;
		let data = {
			pk_transfer: pk_transfer,
			pagecode: this.pageId
		};
		ajax({
			url: '/nccloud/gl/voucher/transDefCard.do',
			data: data,
			success: (res) => {
				if (res.data) {
					this.loadData(res.data);
					if(callback){
						callback(res.data);
					}
				} else {
					this.clearPageData();
				}
			}
		});
	}

	/**
	 * 加载页面数据
	 * @param {} data 
	 */
	loadData(data) {
		if (data.head) {
			this.props.form.setAllFormValue({ [this.formId]: data.head[this.formId] });
			let formId = CARD_IDS.FORM_ID;
			let pk_system = data.head[formId] && data.head[formId].rows[0].values.pk_system || {};
			dealSystemChange(this.props, CARD_IDS.FORM_ID, pk_system);
		}
		if (data.body) {
			this.props.cardTable.setTableData(this.tableId, data.body[this.tableId]);
		}
	}

	clearPageData() {
		this.props.form.EmptyAllFormValue(this.formId)
		let accBook = this.cacheUtil.getSelectAccBook();
		let transSort = this.cacheUtil.getSelectNode();
		let pk_accountingbook = {value:accBook.pk_accountingbook};
		let pk_transsort = {value:transSort.refpk};
		this.props.form.setFormItemsValue(this.formId, {pk_accountingbook, pk_transsort});
		this.props.cardTable.setTableData(this.tableId, { rows: [] });
	}

	//切换页面状态
	toggleShow = () => {
		let status = this.props.getUrlParam('status');
		let pk_transfer = this.props.getUrlParam('id');
		let flag = status === 'browse' ? false : true;//是否可编辑
		this.props.button.setButtonVisible([ 'save', 'cancel', 'addLine', 'delLine', 'copyLine'], flag);
		this.props.button.setButtonVisible(
			[ 'add', 'update', 'delete', 'back', 'cp2others', 'mv2sort', 'refresh' ],
			!flag
		);
		if(pk_transfer){
			this.props.button.setButtonDisabled(['update', 'delete', 'cp2others', 'mv2sort', 'refresh'], false)
		}else{
			this.props.button.setButtonDisabled(['update', 'delete', 'cp2others', 'mv2sort', 'refresh'], true);
		}
		this.props.form.setFormStatus(this.formId, status);
		this.props.cardTable.setStatus(this.tableId, status);
		this.props.cardPagination.setCardPaginationVisible('cardPaginationBtn', !flag);
		if(flag){
			this.updateDelLineBtn();
			let systemValue = this.props.form.getFormItemsValue(CARD_IDS.FORM_ID, CARD_IDS.FORM_PK_SYSTEM);
			dealSystemChange(this.props, CARD_IDS.FORM_ID, systemValue || {});
		} else {
			this.props.button.setButtonVisible(['paste2endline', 'cancel_copy'], false)
		}
		let temp = {
			showCheck: flag,
			showBackBtn: !flag
		}
    	status === 'browse' && (temp.isCopying = false);
   		this.setState({...temp});
	};
	//删除单据
	delConfirm = () => {
		ajax({
			url: '/nccloud/gl/voucher/deleteTransDef.do',
			data: {
				pk_transfer: this.props.getUrlParam('id'),
				ts: this.props.form.getFormItemsValue(this.formId, 'ts').value
			},
			success: (res) => {
				if (res) {
					this.props.linkTo('../list/index.html');
				}
			}
		});
	};

	//保存单据
	saveBill = () => {
		if (this.props.getUrlParam('copyFlag') === 'copy') {
			this.props.form.setFormItemsValue(this.formId, { crevecontid: null });
			this.props.form.setFormItemsValue(this.formId, { ts: null });
		}
		let CardData = this.props.createMasterChildData(this.pageId, this.formId, this.tableId);
		let pageStatus = this.props.getUrlParam('status');
		let url = '/nccloud/gl/voucher/insertTransDef.do'; //新增保存
		if (pageStatus === 'edit') {
			url = '/nccloud/gl/voucher/updateTransDef.do'; //修改保存
		}

		let pk_transfer = this.pk_transfer;
		ajax({
			url: url,
			data: CardData,
			success: (res) => {
				if (res.success) {
					if (res.data) {
						toast({ color: 'success', content: this.state.json['20020SDTRD-000000'],duration: 1 });/* 国际化处理： 保存成功*/
						this.loadData(res.data);
						pk_transfer = res.data.head[this.formId].rows[0].values.pk_transfer.value;
						if (pageStatus == 'edit') {
							updateCache(PKNAME, pk_transfer, res.data, this.formId, DATA_SOURCE);
						} else {
							addCache(pk_transfer, res.data, this.formId, DATA_SOURCE);
						}
					}
				}
					// this.props.pushTo(PATH.CARD, {});
					this.props.setUrlParam({ status: 'browse', id: pk_transfer })
					this.toggleShow();
				
			}
		});
	};

	getButtonNames = (codeId) => {
		if (codeId === 'edit' || codeId === 'add' || codeId === 'save') {
			return 'main-button';
		} else {
			return 'secondary - button';
		}
	};

	//获取列表肩部信息
	getTableHead = (buttons) => {
		let { createButtonApp } = this.props.button;
		return createButtonApp({
			area: 'table_header',
			onButtonClick: buttonClick.bind(this)
		});
	};
	// 复制到其他核算账簿弹框 确定
	handleCp2others = (v) => {
		// let { accbookModalShow } = this.state;
		// accbookModalShow = false;
		// this.setState({ accbookModalShow });
		let pk_accountingbooks = [];
		if (v) {
			v.map((item) => {
				pk_accountingbooks.push(item.refpk);
			});
		}
		this.checkMultiCodeBeforeAction(pk_accountingbooks);
	};
	
	checkMultiCodeBeforeAction = (pk_accountingbooks) => {
		let page = this;
		let codes = [ page.props.form.getFormItemsValue(page.formId, 'transferno').value ];
		let needCp2Arr = []; /* 需要复制到的账簿pk */
		//校验是否有重复数据
		checkMultiCode(page, pk_accountingbooks, codes, (data) => {
			if (!data || data.length === 0) {
				//无重复数据
				let transdefs = [ page.props.form.getFormItemsValue(page.formId, 'pk_transfer').value ];
				//复制到其他核算账簿
				page.setState({ accbookModalShow: false });
				cp2othersFun(page, transdefs, pk_accountingbooks, (res) => {
					if (res.success) {
						toast({ content: page.state.json['20020SDTRD-000001'] });/* 国际化处理： 复制完成！*/
					}
				});
			} else {
				//有重复数据，显示重复数据弹框
				data.map((item, index) => {
					if (!pk_accountingbooks.includes(item.pk_accountingbook)) {
						needCp2Arr.push(item);
					}
				});
				page.setState({
					repeatData: data,
					noRepeatArr: needCp2Arr,
					showCopyCheckModal: true,
					accbookModalShow: false
				});
			}
		});
	};
	/**
	 * 重复数据校验框 确定
	 * data：勾选的需要覆盖的数据
	 */
	handleCopyCheckOK = (data) => {
		let page = this;
		let transdefs = [ page.props.form.getFormItemsValue(page.formId, 'pk_transfer').value ];
		let { noRepeatArr } = this.state;
		let selfArr = [];
		if (data && data.length > 0) {
			data.map((item, index) => {
				selfArr.push(item.pk_accountingbook);
			});
		}
		let newPkrefs = noRepeatArr.concat(selfArr);
		cp2othersFun(page, transdefs, newPkrefs, (res) => {
			if (res.success) {
				toast({ content: page.state.json['20020SDTRD-000001'] });/* 国际化处理： 复制完成！*/
			}
		});
		this.setState({
			showCopyCheckModal: false
		});
	};

	handleMv2sortConfirm = (data) => {
		let page = this;
		let { transsortModalShow } = page.state;
		transsortModalShow = false;
		page.setState({ transsortModalShow });
		page.handleMv2sort(data);
	};

	handleMv2sort = (data) => {
		let page = this;
		let pk_transsort = data.pk_transsort;
		let id = this.props.form.getFormItemsValue(this.formId, 'pk_transfer').value;
		mv2sortFun(page, id, pk_transsort, (res) => {
			if (res.success) {
				toast({ content: this.state.json['20020SDTRD-000002'] });/* 国际化处理： 移动完成*/
				this.handleDel();
			}
		});
	};

	/**
	 * 处理删除事件
	 */
	handleDel = () => {
		let page = this;
		let id = this.props.getUrlParam('id');
		let nextId = getNextId(id, DATA_SOURCE);
		page.props.setUrlParam({id:nextId});
		page.toggleShow();
		deleteCacheById(PKNAME, id, DATA_SOURCE);
		this.getData(nextId);
	};

	handleClear() {}
	goBack = () => {
		let page = this;
		linkToList(page);
	}

	onCheckBoxSelect = (checked) => {
		this.updateDelLineBtn();
	}

	updateDelLineBtn = () => {
		let page = this;
		let checkedRows = page.props.cardTable.getCheckedRows(CARD_IDS.TABLE_ID);
		let disabled = true;
		if(checkedRows && checkedRows.length > 0){
			disabled = false;
		}
		setTimeout(()=>{
			page.props.button.setButtonDisabled(['delLine', 'copyLine'], disabled);
		}, 300);
	}

	updatelistItem = (val)=>{
		this.setState({listItem:val});
	}

	render() {
		let { cardTable, form, button, modal, cardPagination } = this.props;
		let props = this.props;
		let buttons = this.props.button.getButtons();
		let { createForm } = form;
		let { createCardTable } = cardTable;
		const { createCardPagination } = cardPagination;
		let { createButtonApp } = button;
		let { createModal } = modal;
		let { formulaModalState, assidModalState, transsortModalShow, accbookModalShow, showCheck, showBackBtn, json } = this.state;
		let pk_accountingbook = this.props.form.getFormItemsValue(this.formId, 'pk_accountingbook');
		pk_accountingbook = pk_accountingbook && pk_accountingbook.value;
		return (
			<div className="nc-bill-card transfer-def-card">
			<div className="nc-bill-top-area">
				<HeaderArea 
					title = {this.props.getSearchParam('n')}
					initShowBackBtn = {showBackBtn}
					backBtnClick = {this.goBack}
					btnContent = {
						createButtonApp({
							area: 'page_header',
							onButtonClick: buttonClick.bind(this)
						})
					}
					pageBtnContent = {createCardPagination({
						handlePageInfoChange: pageInfoClick.bind(this),
						dataSource: DATA_SOURCE
					})}
				/>
				
				<div className="nc-bill-form-area">
					{createForm(this.formId, {
						onAfterEvent: afterEventForm.bind(this)
					})}
				</div>
				</div>
				<div className="nc-bill-table-area">
					{createCardTable(this.tableId, {
						// high_selectable: {
						// 	enable: true
						// },
						// 框选
						onBatchSelected: this.onCheckBoxSelect.bind(this),
						// 批改和复制excel
						// onBatchChange: onBatchChange.bind(this),
                        adaptionHeight:true,
                        hideSwitch:()=>{return false;},
						tableHead: this.getTableHead.bind(this, buttons),
						modelSave: this.saveBill,
						onAfterEvent: afterEvent.bind(this),
						onBeforeEvent: beforeEvent.bind(this),
						showCheck: showCheck,
						showIndex: true,
						onSelected:(props, moduleId, record, index, status) => {this.onCheckBoxSelect(status)},
						onSelectedAll:(props, moduleId, status, length) => {this.onCheckBoxSelect(status&&length)}
					})}
				</div>

				{createModal('delete', {
					beSureBtnClick: this.delConfirm
				})}
				<FormulaModal
					modal = {props.modal}
					title={formulaModalState.title}
					appcode={props.getSearchParam('c')}
					nodeCode='transfer'
					handleClear={this.handleClear.bind(this)}
					handleFormulaOK={formulaModalState.callback}
					pk_accountingbook={this.orgState ? this.orgState.pk_accountingbook : ''}
					pk_org={this.orgState ? this.orgState.pk_org : ''}
					defaultValue={formulaModalState.defaultValue}
					FormulaModalRef = {init => this.FormulaModal = init}
					updatelistItem = {this.updatelistItem}
				/>
				<AssidModal
					pretentAssData={assidModalState.defaultValue}
					showOrHide={assidModalState.show}
					onConfirm={assidModalState.callback}
					showDisableData={'no'}
					handleClose={() => {
						assidModalState.show = false;
						this.setState({
							assidModalState
						});
					}}
				/>

				<CopyCheckModal
					visible={this.state.showCopyCheckModal}
					repeatData={this.state.repeatData}
					handleCopyCheckOK={this.handleCopyCheckOK.bind(this)}
					handleCancel={() => {
						this.setState({
							showCopyCheckModal: false
						});
					}}
				/>

				<TransSortModal
					show={transsortModalShow}
					onConfirm={this.handleMv2sortConfirm}
					pk_accountingbook={pk_accountingbook}
					json={json}
					onClose={() => {
						transsortModalShow = false;
						this.setState({ transsortModalShow });
					}}
				/>
				<AccountingBookModal
					show={accbookModalShow}
					context={{ appcode: props.getSearchParam('c') }}
					onConfirm={this.handleCp2others}
					json={json}
					onClose={() => {
						accbookModalShow = false;
						this.setState({ accbookModalShow });
					}}
				/>
			</div>
		);
	}
}

Card = createPage({})(Card);

export default Card;

/*2S7LXljdWdGhrCxZ1MFl4i0/jcYg0CI/M/l35xRmsHHDM270ypZGxQFjXbKKRAXA*/